import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { userLogin } from "@/api/user";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import type { IUserInfo } from "./types";

export const useUserStore = defineStore(
  "useUserStore",
  () => {
    const token = ref("");
    const userInfo = ref<IUserInfo>({} as IUserInfo);
    const router = useRouter();

    /** 登录方法 */
    async function login(data: { username: string; password: string }) {
      return new Promise((resolve, reject) => {
        userLogin(data)
          .then((res) => {
            token.value = res.token;
            userInfo.value = res.userInfo;

            userInfoSetLocalStorage();

            ElMessage({
              message: "登录成功",
              type: "success",
            });

            // pinia 设置持久化后，存在异步存储的情况，同步代码马上读取值会出现读不到的情况
            // 故此异步延迟
            setTimeout(() => {
              resolve(true);
            }, 300);
          })
          .catch(() => {
            reject(false);
          });
      });
    }

    /** 退出登录 */
    function logOut() {
      token.value = "";
      userInfo.value = {} as IUserInfo;
      clearLocalStorage();
      router.push("/login");
    }

    /** 用户信息存localstorage,存token */
    function userInfoSetLocalStorage() {
      localStorage.setItem("userInfo", JSON.stringify(userInfo.value));
      localStorage.setItem("token", JSON.stringify(token.value));
    }

    /** 删除本地存储 */
    function clearLocalStorage() {
      localStorage.clear();
    }

    return { login, token, logOut, userInfo };
  },
  { persist: true }, // 设置pinia持久化
);
